import md5 from "md5";
import appDataSource from "../../../db";
import { ValidationError } from "../../../utils/errors";
import { JWTHelper } from "../../../utils/JWTHelper";
import { pick } from "../../../utils/tools";
import SysUserEntity from "../user/Entity";

export interface ILoginBody {
  loginId: string;
  loginPwd: string;
  code: string;
}

export class LoginService {
  public static async login(params: ILoginBody, _req: any) {
    const rep = appDataSource.getRepository(SysUserEntity);

    const user = await rep.findOneBy({ loginId: params.loginId, loginPwd: md5(params.loginPwd) });

    if (!user) {
      throw new ValidationError("账号或密码错误");
    }

    if (user.status === 0) {
      throw new ValidationError("账号已被禁用，请联系管理元");
    }

    const token = JWTHelper.createJwt(pick(user, ["id", "loginId", "nickname"]));
    return { token, ...user };
  }
}
